/*
 * @Author: maskMan
 * @LastEditTime: 2024-04-16 12:40:05
 * @Descripttion:资源管理
 */

export default class ResManager {
  /**
   * @description:加载远程资源
   * @param {string} url 远程资源地址
   * @param {string} ext 资源后缀名
   * @return {Promise}
   */
  static loadUrl<T extends cc.Asset = cc.SpriteFrame>(url: string, ext?: string): Promise<T> {
    return new Promise((resolve) => {
      try {
        const mark = ext ? { ext } : { ext: '.png' }
        cc.assetManager.loadRemote<T>(url, mark, (err, res) => {
          if (!err) {
            return resolve(res)
          } else {
            console.error('error: ', err)
            return resolve(null)
          }
        })
      } catch (error) {
        console.log('error: ', error)
        return resolve(null)
      }
    })
  }
  /**
   * @description:加载文件夹中资源
   * @param {string} url
   * @param {typeof} type
   * @return {Promise<any>}
   */
  static loadRes<T extends cc.Asset = cc.Prefab>(dir: string, types: typeof cc.Asset = cc.Prefab): Promise<T> {
    return new Promise((resolve) => {
      try {
        cc.resources.load<T>(dir, types, (err, res) => {
          if (!err) {
            resolve(res)
          } else {
            console.error('加载资源出错', dir)
            resolve(null)
          }
        })
      } catch (error) {
        console.error('加载资源出错', dir)
        resolve(null)
      }
    })
  }
  /**
   * @description: 加载目标文件夹所有资源
   * @param {string} url
   * @param {typeof} type
   * @return {Promise}
   */
  static loadDir<T extends cc.Asset = cc.Prefab>(path: string, type?: any): Promise<T[]> {
    return new Promise((resolve) => {
      try {
        cc.resources.loadDir<T>(path, type, (err, res) => {
          if (!err) {
            resolve(res)
          } else {
            console.error('error: ', err)
            resolve(null)
          }
        })
      } catch (error) {
        console.error('error: ', error)
        resolve(null)
      }
    })
  }
  /**
   * @description: 加载目标文件夹所有资源
   * @param {string} url
   * @param {typeof} type
   * @return {Promise}
   */
  static loadingDir<T extends cc.Asset = cc.Prefab>(path: string, onProgress, onComplete) {
    return new Promise((resolve) => {
      try {
        cc.resources.loadDir<T>(path, onProgress, onComplete)
      } catch (error) {
        console.error('error: ', error)
        resolve(null)
      }
    })
  }
  /**
   * @description: 预加载场景文件
   * @param {string} sceneName
   * @return {Promise}
   */
  static preloadScene(sceneName: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      try {
        cc.director.preloadScene(sceneName, (err) => {
          if (!err) {
            resolve(true)
          } else {
            console.error('error: ', err)
            resolve(false)
          }
        })
      } catch (error) {
        console.error('error: ', error)
        resolve(false)
      }
    })
  }
}
